import { useData as useJsonData, toSuccess, useEntityManager, useTransaction } from "@sker/core"
import { SysSetting } from "@sker/entities"
import { z } from "zod"
import { useData } from "@sker/runtime"


export const getSetting = async () => {
    const input = z.object({
        key: z.string()
    })
    const body = input.parse(useData())
    return await useEntityManager(async m => {
        const sysSetting = await m.findOne(SysSetting, { where: { code: body.key } })
        return sysSetting?.data || {};
    })
}

export const saveSetting = async () => {
    const input = z.object({
        key: z.string(),
        value: z.any()
    })
    const body = input.parse(useData())
    await useTransaction(async m => {
        if (body.key === 'pc.base') {
            const { data, setData } = useJsonData('data/setting.json', {})
            setData({
                ...data,
                ...body.value
            })
        }
        if (body.key === 'pc.seo') {
            const { data, setData } = useJsonData('data/setting.json', {})
            setData({
                ...data,
                ...body.value
            })
        }
        await m.save(SysSetting, {
            code: body.key,
            data: body.value,
            status: true,
            desc: ''
        })
    })
    return toSuccess(true)
}
